<template>
  <view>
    <MaskLayer v-model:visible="modalVisible" />
    <view class="m-modal" :style="modalClass()">
      <template v-if="modalVisible">
        <view class="content">
          {{ props.content }}

          <slot name="content"></slot>
        </view>
        <view class="btn">
          <view class="close" @tap="close"> 取消 </view>
          <view v-if="!globalStore.modalLoading" class="submit" :style="{ color: globalTheme.basicColor.primary }" @tap="submit">
            确定
          </view>
          <view v-else class="submit">
            <uni-icons class="rotate-box" type="spinner-cycle" size="30" :color="globalTheme.basicColor.primary" />
          </view>
        </view>
      </template>
    </view>
  </view>
</template>
<script setup lang="ts">
export interface ModalProps {
  visible: boolean;
  content: string;
  api: Function;
  params: any;
  callbackMethod?: Function;
  apiBeforeMethod?: Function;
}

const $emit = defineEmits(["close", "submit", "update:visible"]);

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<ModalProps>(), {
  visible: false,
  content: "",
  api: () => null,
  callbackMethod: () => null,
  params: {}
});
const globalStore = useGlobalStore();
const globalTheme = useThemeStore();
let modalVisible = ref(false);

watch(
  () => props.visible,
  flag => (modalVisible.value = flag)
);

watch(
  () => modalVisible.value,
  flag => {
    $emit("update:visible", flag);
  }
);

const modalClass = () => {
  return {
    opacity: modalVisible.value ? 1 : 0,
    zIndex: modalVisible.value ? 10072 : -100
  };
};

// 关闭
const close = () => {
  $emit("close");
  modalVisible.value = false;
};

// 提交
const submit = async () => {
  console.log(props.apiBeforeMethod, "props.apiBeforeMethod");

  if (props.apiBeforeMethod) {
    const flag = await props?.apiBeforeMethod();
    if (!flag) return;
  }
  console.log(0);

  globalStore.modalLoading = true;
  try {
    props.api && (await props.api(props.params));
    props.callbackMethod && props.callbackMethod();
    $emit("submit");
    globalStore.setMessage();
    globalStore.modalLoading = false;
    close();
  } catch (error) {
    modalVisible.value = false;
  }
};

// const keyupSubmit = (e: KeyboardEvent) => {
//   if (e.key === "Enter" && props.visible) {
//     submit();
//   }
// };
// // 绑定回车键事件
// useEventListener(keyupSubmit);
</script>
<style lang="scss" scoped src="./index.scss"></style>
